<?php
namespace Mobile\Controller;
use Think\Controller;
class LoginController extends Controller {


    function __construct()
    {
        parent::__construct();
        $this->c_info;
        $this->M_company = M('Company');
        $this->M_member = M('Member');
        $this->cid = I('post.cid',0,'intval');
    }
    /**
     * 登录
     */
    public function wx_login(){
        if(!$this->cid)
            die($this->ajaxReturn(array('errMsg'=>'没有商家参数!')));
        $this->c_info = $this->M_company->find($this->cid);
        if(!$this->c_info){
            $this->ajaxReturn(array('errMsg'=>' 对不起,商家不存在!'));
            exit;
        }

        $code = I('post.code');
        $encryptedData = I('post.encryptedData');
        $iv = I('post.iv');
        if ($code == '' || $iv == '' || $encryptedData == '') {
            $this->ajaxReturn(array('errMsg'=>'对不起,您没有带资料过来!'));
        }
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->c_info['appid'] . '&secret=' . $this->c_info['appsecret'] . '&js_code=' . $code . '&grant_type=authorization_code';
        $result = $this->http_get($url);
        if ($result) {

            $json = json_decode($result, true);
            if (!$json || !empty($json['errcode'])) {
                return false;
            }
            include_once('./wx/wxBizDataCrypt.php');
            $sessionKey = $json['session_key'];

            $pc = new \WXBizDataCrypt($this->c_info['appid'], $sessionKey);
            $data = '';
            $where['c_id'] = $this->cid;
            $info = $this->M_member->where($where)->find();
            //根据查询的数据判断修改会员还是添加会员
            if ($info) {
            $pc->decryptData($encryptedData, $iv, $data);
            $data = (array)json_decode($data);
            $where['openId'] = $data['openId'];
                $member_data['nickName'] = $data['nickName'];
                $member_data['avatarUrl'] = $data['avatarUrl'];
                $key = $this->u_info['kui_key'] = $member_data['kui_key'] =MD5($data['openId'].time());
                $this->u_info = $this->M_member->where('user_id = ' . $info['user_id'])->save($member_data);
                $this->ajaxReturn(array('kui_key'=>$key));
            } else {
                $this->u_info['openId'] = $member_data['openId'] = $data['openId'];
                $this->u_info['nickName'] = $member_data['nickName'] = $data['nickName'];
                $this->u_info['avatarUrl'] = $member_data['avatarUrl'] = $data['avatarUrl'];
                $this->u_info['c_id'] = $member_data['c_id'] = $this->cid;
                $key = $this->u_info['kui_key'] = $member_data['kui_key'] = MD5($member_data['openId'].time());
                $this->M_member->add($member_data);
                $this->ajaxReturn(array('kui_key'=>$key));
            }
        }
    }
    protected function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

//    返回json数据
     public function output_data($datas, $extend_data = array(), $error = false) {
        $data = array();
        $data['code'] = 200;
        if($error) {
            $data['code'] = 400;
        }
        if(!empty($extend_data)) {
            $data = array_merge($data, $extend_data);
        }
        $data['datas'] = $datas;
        $jsonFlag = 0 && C('debug') && version_compare(PHP_VERSION, '5.4.0') >= 0
            ? JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
            : 0;
        if ($jsonFlag) {
            header('Content-type: text/plain; charset=utf-8');
        }
        if (!empty($_GET['callback'])) {
            echo $_GET['callback'].'('.json_encode($data, $jsonFlag).')';die;
        } else {
            header("Access-Control-Allow-Origin:*");
            echo json_encode($data, $jsonFlag);die;
        }
    }
}
